package top.metaspace.singleton.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import top.metaspace.singleton.LazySingleton;

/**
 * @author panjun
 * @date 2018/6/21.
 * 反射破坏单例
 */
public class ReflectionSingletonTest {
	public static void main(String[] args)
			throws IllegalAccessException, InstantiationException, InvocationTargetException {
		LazySingleton lazySingleton1 = LazySingleton.getInstance();

		Class cls = LazySingleton.class;
		Constructor<LazySingleton>[] constructors = cls.getDeclaredConstructors();
		Constructor<LazySingleton> constructor = constructors[0];
		//因为构造方法是私有的所以必须加setAccessible=true
		constructor.setAccessible(true);
		LazySingleton lazySingleton2 = constructor.newInstance();
		//false 说明当前系统中存在两个LazySingleton对象
		System.out.println(lazySingleton1==lazySingleton2);

		//防止被反射破坏
		AvoidReflectionLazySingleton singleton1 = AvoidReflectionLazySingleton.getInstance();
		Class clsA = AvoidReflectionLazySingleton.class;
		Constructor<AvoidReflectionLazySingleton>[] cs = clsA.getDeclaredConstructors();
		Constructor<AvoidReflectionLazySingleton> c = cs[0];
		c.setAccessible(true);
		//这里会抛出异常，无法创建
		AvoidReflectionLazySingleton singleton2 = c.newInstance();


	}

}
